<template>
  <div class="register-page">
    <h1 class="page-title">光谷智慧交通系统管理平台</h1>
    <main class="register-main">
      <BaseCard
        v-model:formData="formData"
        v-bind="{ formRules, leftBtnText, disableTipLink, tiplinkText }"
        @submit="handleSubmit"
        @tipClick="handleRouterTo"
        ref="baseCard"
        class="register-card"
      >
        <template #card-header>
          <section class="card-header">
            <h1>{{ title }}</h1>
          </section>
        </template>
        <template #form-items>
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model.trim="formData.userName"
              placeholder="请输入用户名"
              :prefix-icon="User"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="loginPwd">
            <el-input
              type="password"
              v-model.trim="formData.loginPwd"
              placeholder="请输入密码"
              show-password
              :prefix-icon="Key"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="confirmPwd">
            <el-input
              type="password"
              v-model.trim="formData.confirmPwd"
              placeholder="请输入确认密码"
              show-password
              :prefix-icon="Key"
              clearable
            ></el-input>
          </el-form-item>
        </template>
      </BaseCard>
    </main>
    <ImageCaptcha v-model="showCaptcha" v-if="showCaptcha" @verified="handleVerified" />
  </div>
</template>

<script setup>
import { ref, useTemplateRef, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { User, Key } from '@element-plus/icons-vue'
import { userRegister, userForgetPwd } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import BaseCard from '@/components/LoginView/BaseCard.vue'
import ImageCaptcha from '@/components/LoginView/ImageCaptcha.vue'

const route = useRoute()
const router = useRouter()
const baseCard = useTemplateRef('baseCard') //没用到

const formData = ref({
  userName: '',
  loginPwd: '',
  confirmPwd: '',
})
const formRules = ref({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 100, message: '用户名长度在1到100个字符', trigger: 'blur' },
  ],
  loginPwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, max: 100, message: '密码长度在1到100个字符', trigger: 'blur' },
  ],
  confirmPwd: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { min: 1, max: 100, message: '确认密码长度在1到100个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.value.loginPwd) {
          callback('两次密码输入不一致')
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

const title = computed(() => {
  switch (route.name) {
    case 'register':
      return '注册'
    case 'forget':
      return '修改密码'
    default:
      return ''
  }
})
const leftBtnText = computed(() => {
  switch (route.name) {
    case 'register':
      return '注册'
    case 'forget':
      return '修改'
    default:
      return ''
  }
})
const tiplinkText = computed(() => {
  switch (route.name) {
    case 'register':
      return `已有账号？点我登录`
    case 'forget':
      return `取消修改？点我登录`
    default:
      return ''
  }
})
const disableTipLink = ref(false)
const showCaptcha = ref(false)

const handleSubmit = () => {
  showCaptcha.value = true
}
const handleVerified = () => {
  switch (route.name) {
    case 'register':
      handleRegister()
      break
    case 'forget':
      hanleForget()
      break
  }
}
const handleRegister = async () => {
  try {
    await userRegister(formData.value)
    ElMessage({
      message: '注册成功',
      type: 'success',
    })
    router.push({ name: 'login' })
  } catch (error) {
    switch (error.status) {
      case 401: {
        ElMessageBox.confirm('注册失败,用户名已存在,是否跳转到登录页面', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: (action) => {
            switch (action) {
              case 'confirm':
                router.push({ name: 'login' })
                break
            }
          },
        })
        break
      }
    }
  }
}
const hanleForget = async () => {
  try {
    await userForgetPwd(formData.value)
    ElMessage({
      message: '修改成功',
      type: 'success',
    })
    router.push({ name: 'login' })
  } catch (error) {
    switch (error.status) {
      case 404: {
        ElMessageBox.confirm('用户名未注册,是否跳转到注册页面', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          callback: (action) => {
            switch (action) {
              case 'confirm':
                router.push({ name: 'register' })
                break
            }
          },
        })
        break
      }
      case 401: {
        ElMessageBox.alert('暂无权限修改密码', {
          confirmButtonText: '确定',
          type: 'warning',
        })
        break
      }
      case 400: {
        ElMessageBox.alert('新密码不能与旧密码相同', {
          confirmButtonText: '确定',
          type: 'warning',
        })
        break
      }
    }
  }
}
const handleRouterTo = () => {
  router.push({ name: 'login' })
}
</script>

<style lang="scss" scoped>
.register-page {
  position: relative;
  min-height: 100vh;
  background-image: url('img/背景2.gif');
  background-repeat: no-repeat;
  background-size: cover;
  .page-title {
    position: relative;
    top: 8rem;
    font-size: 2.5rem;
    color: #fff;
    text-align: center;
  }
  .register-main {
    position: absolute;
    top: 55%;
    left: 50%;
    width: 22rem;
    transform: translate(-50%, -50%);
    :deep(.register-card) {
      .card-header {
        h1 {
          text-align: center;
          font-size: 1.2rem;
        }
      }
      .password-operation {
        display: flex;
        justify-content: space-between;
        margin-top: 0.7rem;
        .forget-password {
          align-content: center;
          .el-link {
            display: block;
            a {
              text-decoration: none;
              color: inherit;
              cursor: inherit;
            }
          }
        }
      }
      .el-card__body {
        padding-bottom: 1.2rem;
      }
    }
  }
}
</style>
